package com.m2bshop.shop.common;

import org.springframework.web.multipart.MultipartFile;



import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

public class imgUtils {

    //上传图片工具类
    public String uploadImg(MultipartFile multipartFile, String dir) throws IOException {
        File directory = new File("");//参数为空
        String courseFile = directory.getCanonicalPath() ;
        String serverpath ="/BMC/WebImg?path=";
        File f = new File(this.getClass().getResource("/").getPath());
        System.out.println(f);
        String imgprefix = courseFile+"//照片数据库";
        String filename = "";
        String imgsuffix ="";
        String newFilename ="";
        try {
            filename = multipartFile.getOriginalFilename();//文件名;
            imgsuffix = filename.substring(filename.lastIndexOf("."));
            newFilename = UUID.randomUUID().toString() + imgsuffix;
            File newfile = new File(imgprefix +"/"+ dir+"/" + newFilename);
            if (!newfile.exists()) {
                newfile.mkdirs();
            }
            multipartFile.transferTo(newfile);
        }
        catch (IOException e){
            e.printStackTrace();
            return "fail";
        }
        String jiami =  imgprefix+"/"+dir+"/"+newFilename;
        String SS = URLEncoder.encode(jiami);
        return serverpath +SS;
    }
}
